import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import VideoContainer from '../VideoContainer';
import ToolBar from '../ToolBar';
import { getTools } from '@/conf';
import HeaderMenu from '../HeaderMenu';
import Vocational from '../Vocational';
import UserInforMation from '../UserInforMation';
import OnRingModal from '../OnRing';
import { RootState } from '@/store';
import Message from '@/utils/message';
import { useTranslation } from 'react-i18next';
import { notification, Modal } from 'antd';

import './styles/agent_main.less';

import { message } from 'antd';

import {
	getuserforminfo,
	getsessiondetail,
	getTestimoneyList,
	getVariablesList,
	getTTSOption,
	saveSessionForm,
	getCustomerAndBusinessVariables,
	getAllRoleWithBusiness,
	getBizflowQualityRecord,
	getConfigList
} from '@/api';
import { setSessionData, clearSessionData, setJoinMembers, setMembersLeave } from '@/store/reducers/session';

import { setAgentInfo, logout, resetAmsStatus } from '@/store/reducers/agent';

import { clearChatRecord, setChatRecord } from '@/store/reducers/chatRecord';
import { Breadcrumb, Layout, Spin } from 'antd';
import ReconnectMessageBox from '../VideoContainer/ReconnectMessageBox';
const { Header, Content } = Layout;
import {
	onCancelRing,
	onStreamAdd,
	onStreamEnd,
	StreamAdd,
	StreamEnd,
	onCustomerQuitSession,
	onCustomerJoinSession,
	hangup,
	onDrop,
	onCcsDrop,
	ccsError,
	systemError,
	rejectSession,
	onAgentQuitSession,
	receiveCustomizeMessage,
	onTextMessage,
	onAgentJoinSession,
	onResourceMessage,
	sendTextMessage,
	shareResourceWithFileInfo,
	joinSession,
	onRenderMediaStatus,
	onPublishMediaStatus,
	onAmsConnectStatus,
	onOtherReconnecting,
	onOtherResumeConnect,
	onSessionConnectStatus,
	initWithLoginData,
	onInvitationProgress,
	onVariableChange,
	addScreenWatermark
} from '@/utils/lib';
import { useDispatch, useSelector } from 'react-redux';
import {
	setCustomerStreamList,
	setAgentStreamList,
	clearCustomerStreamList,
	clearAgentStreamList,
	clearOtherStreamList,
	setAgentLeave,
	setOtherLeave,
	setCustomerLeave,
	clearRenderStream
} from '@/store/reducers/stream';
import { setCustomerMessage, setCustomerMessageList } from '@/store/reducers/message';

import { setMessage } from '@/store/reducers/newMessage';

import { compareArraysWithId, formatSessionMessageRecords, userInSessionRecord } from '@/utils';

import { ScreenSyncStateProps, useScreenSync } from '../Context/ScreenSyncContext';
import useSyncState from '../hooks/useSyncState';

import store from '@/store';
import { useBusiness, IBusinessName, IBusinessStatus, ReceiveBroadcastMap } from '../Context/BusinessContext';
import { useMenuContext } from '../Context/MenuContext';
import { IStream, useStream } from '../Context/StreamContext';
import RecordScreenTimer from '../RecordScreenTimer';
import styled from '@emotion/styled';
import { IUserData } from '../UserInforMation/UserInfo';
import { uploadFile } from '@/utils/upload';
import AgentService, { ILayout, IEvent, Code } from '@/modules/Agent';

import { endScreenShare, saveStopScreenShareRecord, deleteWhiteboard, deletePdfWhiteboard } from '../Context/utils/requestBusiness';

import { jwtDecode } from 'jwt-decode';
import RecordPoint from '../RecordPoint';
import ZcoSubTitle from '@/modules/subTitle/subtitle';
import VariablePreview from '../PreviewModal/VariablePreview';
import WhiteBoard from '../WhiteBoard';
import PdfWhiteBoard from '../PDFWhiteBoard';
import { useTTSBoardCast } from '../Context/TTSBoardCastContext';
import backgroundEffect from '@/utils/BackgroundEffect';
import { resizeWin } from '@/utils/resize';
import { t } from 'i18next';
import { setLocalAmsStatus, setRemoteStatus, clearNetworkStatusData, setLocalCcsStatus, resetNetworkStatus } from '@/store/reducers/networkStatus';
import MediaStatus from '@/modules/media-status/MediaStatus';
import { ICurrentTab, IJoinedMembers, IOperationName, IOperationType } from '@/modules/interface';
import AgentManagement from '../AgentManagement';
import QualityTestingResult from '../QualityTestingResult';
import ErrorAlert from '../Alert';
import WaitingBox from '../ChatWindow/WaitingBox';
import RegionalScreenRecording from '../../components/RegionalScreenRecording/index';
import clog from '@/modules/CLog';
import { log, warn } from 'fabric/fabric-impl';
import RecordingAlert from '../RecordingAlert';
import AudioRing from '@/components/AudioRing';
import CascaderSelect from '../BusinessOperation/FillForm/CascaderSelect';
import Client from '@/modules/libs/Client';
import { startMedia } from '@/modules/IVCS';
import { useNavigate } from 'react-router-dom';
import Humanflow from '@/components/Humanflow';
import SpeakingTips from '@/components/SpeakingTips';
import CustomerViewMarkDialog from '../CustomerStreamMark';
import SummaryButton from '../SessionSummary/SummaryButton';
import SummaryForm from '../SessionSummary/SummaryForm';
import ServiceRecord from '../ServiceRecords';
import ChangePassword from '../Login/ChangePassword';
import AudioRecordError from '@/components/AudioRecordError';
const moment = require('moment');

const initialUserInfo = [
	{
		fullName: '',
		idCard: '',
		phoneNumber: ''
	}
];

interface IMembersProps {
	id: string;
	clientId: string;
	username: string;
	userRole: string;
	label: 'customer' | 'agent' | null;
}

interface customerViewMarkInfo {
	isShow: boolean;
	width: number;
	height: number;
	clientId: string;
	videoId: string;
}

const WidgetMainWrapper = styled(Layout)`
	background: none;
	overflow: hidden;
`;

const WidgetLayout = styled(Layout)`
	width: 100%;
	/* max-width: 1280px; */
	min-width: 1024px;
	/*margin: 50px auto 0px; */
	padding: 16px;
	background: none;
	height: 100%;
	/*padding-top: 70px;*/
	justify-content: center;
`;

const WidgetLayoutSider = styled(Layout.Sider)`
	width: 340px;
	box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.12);
	border-radius: 2px;
`;

const WidgetVideoWrapper = styled(Content)`
	margin: 0 16px;
	padding: 14px 36px 0px;
	background: #ffffff;
	box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.12);
	border-radius: 2px;
`;

const VocationalDiv = styled.div`
	display: ${(props: { layout: string }) => (props.layout === 'full' || props.layout === 'right' ? '' : 'none')};
	max-height: 100%;
	height: 100%;
	background: #fafbfc;
	display: flex;
	flex-flow: column;
`;

const FullWidgetMessage = styled.div`
	position: relative;
	height: 100%;
`;

const NormalWidgetMessage = styled.div`
	position: relative;
	height: calc(100% - 226px);
`;

const notificationKey = 'amsNetworkStatus';

const iFailedInviteProgressType = ['canceled', 'notfound', 'timeout', 'offday', 'offtime', 'scenariodisabled', 'otherCustomerAccept', 'multiCustomerForbidAI', 'rejected', 'ringingTimeout'];

const Agent = () => {
	const { t } = useTranslation();
	const dispatch = useDispatch();

	const { login, session, customerStreams, agentStreams, otherStreams, customerMessage, customerMessageList, agent, networkStatus } = useSelector((state: RootState) => state);
	const { setScreenSyncState, screenSyncState, startCoBrowsing, onScreenSyncEnd } = useScreenSync();
	const {
		membersJoin,
		membersLeave,
		getMembersLabel,
		getCustomerMembers,
		sendBusiness,
		setAgentName,
		record,
		setRecord,
		setAllMembers,
		customerMembers,
		setCustomerMembers,
		BusinessTaskMap,
		setBusiness,
		notifyOtherAgents,
		setBizScenarioId,
		agentLeaveSession,
		screenId,
		setScreenId,
		recordRegion,
		setRecordRegion,
		cancelBusiness
	} = useBusiness();
	const { menuState, setOuterFuc, setMainContent, mainContent, chiefs, setRoomId, setIsJoinSession, loading, setLoading, setServiceMonitoring, serviceMonitoringView } = useMenuContext();
	const { streamAdd, streamEnd, clearStreams, streams, setStreams, recordPoint, setRecordPoint, setBoardCastStream, boardCastStream, audioStreams, setAudioStreams, setSmallStream, updateStream } =
		useStream();
	const { setWhiteBoardBtnStatus, setSharePdfBtnStatus } = useBusiness();
	const [customerClinentId, setCustomerClientId] = useState<string | null>(null);
	const [tools, setTools] = useSyncState(getTools('base'));
	const [isScreenSyncCall, setIsScreenSyncCall] = useSyncState<boolean>(false);
	const [showAgentManagement, setShowAgentManagement] = useSyncState<boolean>(false);

	const sendScreenSyncRef = useRef<boolean>(false);

	const [zcoSubTitle, setZcoSubTitle] = useSyncState<any>(null);

	const { setTTSBoardCastStats, setBoardCastModal, setEditModal } = useTTSBoardCast();

	const [amsStatus, setAmsStatus] = useState('');
	const [notificationStatus, setNotificationStatus] = useState(false);

	const [currentTab, setCurrentTab] = useState<ICurrentTab>(AgentService.configure.currentTab as ICurrentTab);

	const [alertMessage, setAlertMessage] = useState<string>('');

	const [recordingModalVisible, setRecordingModalVisible] = useState<boolean>(false);

	const [recordingModalText, setRecordingModalText] = useState<string>('');

	const [showRelogin, setShowRelogin] = useSyncState<boolean>(false);

	const [curTips, setCurTips] = useState<string>('');

	const [humanflowSteps, setHumanflowSteps] = useSyncState<any>(null);

	const navigate = AgentService.useAsWidget ? null : useNavigate();

	const [showSummaryForm, setShowSummaryForm] = useState<boolean>(false);

	const [isDialogCustomerViewMark, setIsDialogCustomerViewMark] = useState<customerViewMarkInfo>({
		isShow: false,
		videoId: '',
		clientId: '',
		width: 0,
		height: 0
	});
	const [showChangePassword, setShowChangePassword] = useState<boolean>(false);

	/**
	 * 退出实时标注
	 */
	const closeCustomerViewMarkDialog = () => {
		cancelBusiness(isDialogCustomerViewMark.clientId, IBusinessName.CUSTOMER_VIEW_MARK);
		setIsDialogCustomerViewMark({
			isShow: false,
			videoId: '',
			clientId: '',
			width: 0,
			height: 0
		});
	};

	useEffect(() => {
		AgentService.addEventListener(resp => {
			if (resp.event === IEvent.AMS) {
				onAmsConnectStatusEvent(resp.data.data);
			}
			if (resp.event === IEvent.OTHER_RECONNECTING) {
				onOtherReconnectingEvent(resp.data.data);
			}
			if (resp.event === IEvent.SESSION_CONNECT_STATUS) {
				onSessionConnectStatusEvent(resp.data.data);
			}
			if (resp.event === IEvent.INVITATION_PROGRESS) {
				onInvitationProgressEvent(resp.data.data);
			}
			if (resp.event === IEvent.STREAM_ADD) {
				onStreamAddEvent(resp.data.data);
			}
			if (resp.event === IEvent.STREAM_END) {
				onStreamEndEvent(resp.data.data);
			}
			if (resp.event === IEvent.CCS_DROP) {
				onCcsDropEvent(resp.data.data);
			}
			if (resp.event === IEvent.ON_RING) {
				onRingCall(resp.data.data);
			}
			if (resp.event === IEvent.VARIABLE_CHANGE) {
				onVariableChangeEvent(resp.data.data);
			}
			if (resp.event === IEvent.SYNC_MESSAGE) {
				onSyncMessageEvent(resp.data.data.data);
			}
			if (resp.event === IEvent.REAL_TIME_QUALITY) {
				onRealTimeQualityEvent(resp.data.data);
			}
			if (resp.event === IEvent.ANSWER && resp.data.code === Code.ANSWER_SUCCESS) {
				initZcoSubTitle();
				getSessionData(AgentService.sessionId);
				const customerClientId = AgentService.sessionMembers.find(item => item.role === 'customer')?.id || '';
				if (customerClientId && isScreenSyncCall()) {
					setScreenSyncState({ ...screenSyncState(), clientId: customerClientId });
					startCoBrowsing('request-customer-size');
				}
				setRecordPoint({
					...recordPoint(),
					recordingId: AgentService.recordingPoint.recordingId,
					userName: AgentService.recordingPoint.userName,
					userRole: 'agent',
					userId: AgentService.recordingPoint.userId
				});
				// 人工工作流
				setHumanflowSteps(AgentService.getHumanflowSteps());
			}
			if (resp.event === IEvent.ANSWER && resp.data.code === Code.ANSWER_ERROR) {
				hangUp({ code: 400, reason: 'answer error' });
				setLoading(false);
			}
			if (resp.event === IEvent.AGENT_JOIN_SESSION) {
				onAgentJoinSessionEvent(resp.data.data);
			}
			if (resp.event === IEvent.AGENT_QUIT_SESSION) {
				onAgentQuitSessionEvent(resp.data.data);
			}
			if (resp.event === IEvent.UPDATE_CLIENT_INFO) {
				onClientInfo(resp.data.data);
			}

			if (resp.event === IEvent.CUSTOMER_JOIN_SESSION) {
				onCustomerJoinSessionEvent(resp.data.data);
			}
			if (resp.event === IEvent.CUSTOMER_QUIT_SESSION) {
				onCustomerQuitSessionEvent(resp.data.data);
			}
			if (resp.event === IEvent.TEXT_MESSAGE) {
				onTextMessageEvent(resp.data.data);
			}
			if (resp.event === IEvent.RESOURCE_MESSAGE) {
				onResourceMessageEvent(resp.data.data);
			}
			if (resp.event === IEvent.SYSTEM_ERROR) {
				systemErrorEvent(resp.data.data);
			}
			if (resp.event === IEvent.CCS_ERROR) {
				InitializationData();
				sessionCcsErrorEventListener(resp.data.data);
			}
			if (resp.event === IEvent.ON_DROP) {
				onDropEvent(resp.data.data);
			}
			if (resp.event === IEvent.PUBLISH_MEDIA_STATUS) {
				onPublishMediaStatusEvent(resp.data.data);
			}
			if (resp.event === IEvent.RENDER_MEDIA_STATUS) {
				onRenderMediaStatusEvent(resp.data.data);
			}
			if (resp.event === IEvent.OTHER_RESUME_RECONNECT) {
				onOtherResumeConnectEvent(resp.data.data);
			}
			if (resp.event === IEvent.SET_AGENT_STATUS) {
				if (configure.currentTab === 'agentManagement' && AgentService.agentStatus.isChief && !AgentService.sessionId && AgentService.agentStatus.checkIn && AgentService.agentStatus.ready) {
					changeTabs('sessionService');
				}
			}
			if (resp.event === IEvent.CUSTOMIZE_MESSAGE) {
				receiveCustomizeMessageData(resp.data.data);
			}
			if (resp.event === IEvent.HANG_UP) {
				InitializationData();
			}
			if (resp.event === IEvent.OTHER_WORK && resp.data.code === Code.APPLY_OTHER_WORK_SUCCESS) {
				Message.normal(t('setting-otherWork-save-success'));
			}
			if (resp.event === IEvent.PAGE_LEAVE) {
				console.log('page leave');
			}
			if (resp.event === IEvent.LOGOUT) {
				InitializationData();
				ZcoIM.destory();
				if (navigate) {
					navigate('/login');
					window.location.reload();
				}
			}
			if (resp.event === IEvent.ON_UPGRADE) {
				onUpgrade(resp.data.data);
				setRecordPoint({
					...recordPoint(),
					recordingId: AgentService.recordingPoint.recordingId,
					userName: AgentService.recordingPoint.userName,
					userRole: 'agent',
					userId: AgentService.recordingPoint.userId
				});
			}
			if (resp.event === IEvent.ACCEPT_UPGRADE && resp.data.code === Code.ACCEPT_UPGRADE_ERROR) {
				setLoading(false);
				AgentService.rejectUpgrade(AgentService.acceptCallMode.receiveMediaType, resp.data.data);
				if (resp.data?.data?.message === 'membersOverrunNotAllowedUpgrade') {
					Message.error(t('unable-upgrade-due-to-new-visitor'));
				}
			}
			if (resp.event === IEvent.ACCEPT_UPGRADE && resp.data.code === Code.ACCEPT_UPGRADE_SUCCESS) {
				setLoading(false);
				AgentService.startVideo();
				setRecordPoint({
					...recordPoint(),
					recordingId: AgentService.recordingPoint.recordingId,
					userName: AgentService.recordingPoint.userName,
					userRole: 'agent',
					userId: AgentService.recordingPoint.userId
				});
			}
			if (resp.event === IEvent.REQUEST_UPGRADE && resp.data.code === Code.REQUEST_UPGRADE_ERROR) {
				const { media, error } = resp.data.data;
				if (error.message === 'membersOverrunNotAllowedUpgrade') {
					Message.error(t('unable-upgrade-due-to-new-visitor'));
				} else if (error?.code === '60000') {
					if (media === 'video') {
						Message.error(t('agent-no-authorize-microphone-or-camera'));
					} else {
						Message.error(t('agent-no-authorize-microphone'));
					}
				} else if (error?.code === '5006' && error?.message?.status === 'membersOverrunNotAllowedUpgrade') {
					Message.error(t('multi-party-not-support-upgrading'));
				} else if (error?.code === '5006' && error?.message?.status === 'upgradeRequested') {
					Message.error(t('client-upgrading'));
				}
				// show error toast
				setLoading(false);
				// setRequestWaiting({});
			}
			if (resp.event === IEvent.REQUEST_UPGRADE && resp.data.code === Code.REQUEST_UPGRADE_SUCCESS) {
				const { media } = resp.data.data;
				setRequestWaiting({ status: true, type: media });
			}

			if (resp.event === IEvent.START_VIDEO && resp.data.code === Code.START_VIDEO_SUCCESS) {
				AgentService.setIsIMSession(false);
				ZcoIM.setWebTitle({ title: t('chat-window'), type: AgentService.acceptCallMode?.callMediaType, members: AgentService.sessionMembers?.length });
			}
			if (resp.event === IEvent.START_VIDEO && resp.data.code === Code.START_VIDEO_ERROR) {
				hangUp({ code: 400, reason: 'start video error' });
				setLoading(false);
			}
			if (resp.event === IEvent.GET_SESSION_MEMBERS && resp.data.code === Code.GET_SESSION_MEMBERS_SUCCESS) {
				updateSessionMembersAndStreams(resp.data.data.members);
			}
			if (resp.event === IEvent.ON_CCS_RESUME_SUCCESS) {
				updateSessionMembersAndStreams(resp.data.data.members);
			}
			if (resp.event === IEvent.RECORDING_ALERT) {
				if (!resp.data.data.systemRecordingId && AgentService.isAutoSystemRecord) {
					setRecordingModalVisible(true);
					setRecordingModalText(`${t('recording-start-failed')}`);
					playRecordErrorAudio();
				}
			}
			if (resp.event === IEvent.ON_SESSION_RECORD_CRASH) {
				console.log(resp.data.data.recordingId, 'ON_SESSION_RECORD_CRASH', AgentService.recordingAlert.systemRecordingId);
				if (resp.data.data.recordingId === AgentService.recordingAlert.systemRecordingId) {
					//系统录像
					setRecordingModalVisible(true);
					setRecordingModalText(`${t('recording-interruption')}`);
					playRecordErrorAudio();
					setRecordPoint({
						...recordPoint(),
						recordingId: '',
						userName: AgentService.recordingPoint.userName,
						userRole: 'agent',
						userId: AgentService.recordingPoint.userId
					});
				} else if (resp.data.data.recordingId === AgentService.recordingAlert.screenRecordingId) {
					//录屏
					Message.warning(t('screen-recording-file-storage-interruption'));
					cancelBusiness(record().clientId, IBusinessName.RECORD_SCREEN);
				} else if (resp.data.data.recordingId === AgentService.recordingAlert.regionalScreenRecordingId) {
					//区域录屏
					Message.warning(t('regional-screen-recording-file-storage-interruption'));
					cancelBusiness(recordRegion().clientId, IBusinessName.REGIONAL_SCREEN_RECORDING);
				}
			}
			if (resp.event === IEvent.ON_SYSTEM_RECORD_UPDATE) {
				// {event:'system-record',status:'start'|'stop',recordId:''}
				console.log('ON_SYSTEM_RECORD_UPDATE ', resp);

				setRecordPoint({ ...recordPoint(), recordingId: resp.data.data.status === 'start' ? resp.data.data.recordId : '' });
			}

			if (resp.event === IEvent.OBSERVER_JOIN_SESSION) {
				observerJoinSession(resp.data.data);
			}

			if (resp.event === IEvent.CUSTOMER_VIEW_MARK) {
				console.log('CUSTOMER_VIEW_MARK data', resp.data.data);
				const data = resp.data.data;
				if (data.data?.status === IBusinessStatus.ACCEPTED) {
					setIsDialogCustomerViewMark({
						isShow: true,
						width: data.data?.data?.width,
						height: data.data?.data?.height,
						clientId: data?.from,
						videoId: data.data?.data?.data?.videoId
					});
					console.log('isDialogCustomerViewMark', isDialogCustomerViewMark);
				}
			}

			if (resp.event === IEvent.MODIFY_PASSWORD) {
				setShowChangePassword(true);
			}

			if (resp.event === IEvent.NEED_UPDATE_PASSWORD) {
				const needUpdatePassword = resp.data.data.needUpdatePassword;
				// 目标日期
				const targetDate = moment(needUpdatePassword);
				// 计算天数差异
				const daysDifference = targetDate.diff(moment(), 'days');
				console.log('NEED_UPDATE_PASSWORD data', daysDifference);
				if (daysDifference > 14) {
					return;
				}
				// 超期前2周内，用户每次登录成功提示用户更新密码，弹出提示弹框，弹框文案显示“您当前使用的登录密码还有xx天到期，请及时更新登录密码”，弹框显示“我知道了”和“修改密码”两个按钮。
				Modal.confirm({
					content: `您当前使用的登录密码还有${daysDifference}天到期，请及时更新登录密码`,
					cancelText: '我知道了',
					okText: '修改密码',
					icon: null,
					wrapClassName: 'change-password-confirm-modal',
					onOk() {
						setShowChangePassword(true);
					},
					onCancel() {
						console.log('Cancel');
					}
				});
			}
		});

		return () => {
			AgentService.removeEventListener();
			window.sessionStorage.clear();
		};
	}, []);

	useEffect(() => {
		setTimeout(() => {
			initIM();
		}, 200);
		init();
		// console.log(AgentService.validGroups, 'AgentService.validGroups');
		getSysConfigList();

		AgentService.addInviteEventLinstener((info: any) => {
			if (info.type === 'operation' && !AgentService.isIMSession) {
				if (AgentService.operationMap.has(IOperationName.INVITE)) {
					setStreams([
						...streams(),
						{
							id: IOperationName.INVITE + AgentService.getOperationWithId(IOperationName.INVITE).data.id,
							label: 'agent',
							audioOnly: false,
							clientId: '',
							muteStatus: false,
							videoId: '',
							streamMode: 'video',
							role: '',
							userName: '',
							isScreenSyncMode: false
						}
					]);
				}
			}
		});

		const { configure } = AgentService;
		if (configure.pocSetting.autoCheckin) {
			const groupsId = AgentService.validGroups.map(item => {
				return { id: item.id, name: item.name };
			});
			checkedGroup(groupsId);
		}
		if (configure.pocSetting.autoReady) {
			agentReady();
		}

		AgentService.getUnfinishedSummary();

		return () => {
			AgentService.removeInviteEventListener();
		};
	}, []);

	const playRecordErrorAudio = async () => {
		const ring = document.getElementById('record-error-source') as HTMLAudioElement;
		try {
			(await ring) && ring.play();
		} catch (error) {
			console.log(error, 'start ring error');
			setTimeout(() => {
				ring && ring.play();
			}, 1000);
		}
	};
	const pauseRecordErrorAudio = () => {
		const ring = document.getElementById('record-error-source') as HTMLAudioElement;
		ring && ring.pause();
		setTimeout(() => {
			ring && ring.pause();
		}, 1000);
	};

	// 签入分组
	const checkedGroup = async (values: any) => {
		setLoading(true);
		try {
			const data = await AgentService.checkinSystem(values);
			if (data?.code === 200) {
				setLoading(false);
			}
		} catch (error) {
			console.log('checkin error', error);
			setLoading(false);
		}
	};

	const agentReady = async () => {
		try {
			const data = await AgentService.agentReady();
			console.log(data);
			if (data.code == 200) {
				setLoading(false);
			}
		} catch (error) {
			console.log(error, 'ready error');
			setLoading(false);
		}
	};

	useEffect(() => {
		window.addEventListener(
			'popstate',
			function () {
				this.window.location.reload();
			},
			false
		);
		return () => {
			window.removeEventListener('popstate', () => {}, false);
		};
	}, []);

	useEffect(() => {
		setTimeout(() => {
			if (ZcoIM) {
				let lng = AgentService.getLanguage() === 'zh' ? 'zh' : AgentService.getLanguage() === 'en-US' ? 'en' : 'tw';
				ZcoIM.setLanguage(lng);
			}
		}, 200);
	}, [AgentService.getLanguage()]);

	const updateSessionMembersAndStreams = (members: any) => {
		const { added, deleted } = compareArraysWithId(AgentService.sessionMembers, members);
		console.log(members, 'get session members success', added, deleted);
		added.forEach(item => {
			if (!AgentService.sessionMembers.find(ele => ele.id === item.id)) {
				AgentService.addSessionMembers(item);
			}
		});
		deleted.forEach(item => {
			AgentService.removeSessionMembers(item.id);
			streamEnd(item.id);
			if (streams().length === 1) {
				hangUp({ code: 200, reason: 'customer quit' });
				MediaStatus.clearMediagData();
				dispatch(clearNetworkStatusData());
			} else {
				dispatch(setRemoteStatus({ id: item.id, status: 'reconnect_failed' }));
			}
			ZcoIM.setWebTitle({ title: t('chat-window'), type: AgentService.acceptCallMode?.callMediaType, members: AgentService.sessionMembers?.length });
			if (AgentService.sessionId) {
				ZcoIM.setSystemMessage(item);
			}
		});
	};

	const resizeObserver = new ResizeObserver(entries => {
		// console.log(entries[0].contentRect);
	});

	if (AgentService.rootContainer) {
		resizeObserver.observe(AgentService.rootContainer);
	}

	const initIM = () => {
		if (document.getElementById('widget-message-box') === null) {
			return;
		}
		//IM组件初始化
		ZcoIM.init(undefined, undefined, 'web', 'widget-message-box', true, []);
		ZcoIM.setLanguage('en');
		console.warn(document.getElementById('widget-message-box'));
		ZcoIM.onSendTextMessage(async (data: any) => {
			sendTextMessage(data.data)
				.then(resp => {
					ZcoIM.sendMessage(data, 'ok');
				})
				.catch(e => {
					ZcoIM.sendMessage(data, 'failed');
				});
		});
		ZcoIM.onSendResourceMessage(async (data: any) => {
			console.log(data, 'ResourceMessage');
			try {
				let resp = await uploadFile(data.data.file);
				if (resp) {
					let msgData = { ...resp, type: data.data.type };
					data.data = msgData;
					console.log(data, 'uploadFile');
					shareResourceWithFileInfo(data.data.type, resp, 'others')
						.then(resp => {
							ZcoIM.sendMessage(data, 'ok');
						})
						.catch(e => {
							ZcoIM.sendMessage(data, 'failed');
						});
				} else {
					ZcoIM.sendMessage(data, 'failed');
				}
			} catch (error) {
				console.log(error, 'onSendResourceMessage');
				ZcoIM.sendMessage(data, 'failed');
			}
		});
		ZcoIM.onRequestAudioCall(() => {
			const customerClientIds = AgentService.sessionMembers.filter(item => item.role === 'customer') || [];
			customerClientIds.map(item => {
				AgentService.requestUpgrade('audio', item.id);
			});
		});
		ZcoIM.onRequestVideoCall(() => {
			const customerClientIds = AgentService.sessionMembers.filter(item => item.role === 'customer') || [];
			customerClientIds.map(item => {
				AgentService.requestUpgrade('video', item.id);
			});
		});

		setOuterFuc((prevState: any) => ({ ...prevState, hangUp: hangUp }));
	};

	useEffect(() => {
		if (AgentService.userData?.isScreenSyncMode) {
			setIsScreenSyncCall(AgentService.userData?.isScreenSyncMode);
			setScreenSyncState({ ...screenSyncState(), status: 'start' });
		}
	}, [AgentService.userData]);

	/** 初始化 */
	const init = async () => {
		// 如果 AgentService.token 为空，返回登录页
		if (!AgentService.token && navigate) {
			navigate('/login');
			window.location.reload();
		}
		try {
			let data: any = jwtDecode(AgentService.token);
			dispatch(
				setAgentInfo({
					...agent,
					id: data.data.id || ''
				})
			);
			if (AgentService.validGroups && AgentService.validGroups.length > 0) {
				try {
					// onDrop(onDropEvent);
					// onRing(onRingCall);
				} catch (error) {
					nav2Login();
				}
			}
			/** 存储当前坐席登录信息 */
			AgentService.setUser({ userName: data.data.userName, id: data.data.id, isDisabled: data.data.isDisabled, isRobot: data.data.isRobot, org: data.data.org, role: data.data.role });
		} catch (error) {
			nav2Login();
			console.log(error);
		}
	};
	const [onRingView, setonRingView] = useState<boolean>(false);
	const [formId, setFormId] = useState<string | number>('');
	const [customerSubmitInfo, setCustomerSubmitInfo] = useSyncState<IUserData[]>(initialUserInfo);

	//清空sessionStorage
	const clearSessionStorage = () => {
		sessionStorage.setItem('sessionId', '');
		sessionStorage.setItem('customerSubscribeId', '');
	};

	const observerJoinSession = data => {
		if (data) {
			sessionStorage.setItem('sessionId', data.sessionId);
			setIsJoinSession(true);
			// setIsKickPerson(true);
			// setShowAgentManagement(false);
			// let copyTabs = [...tabs()];
			// copyTabs = copyTabs.filter(item => item.key === 'sessionService');
			// setTabs(copyTabs);
			//设置班组长属性
			changeTabs('sessionService');
			setLoading(false);
			const { members, clientId, roomId, recordingId = '' } = data.sessionData;
			const { publicationId = '' } = data;
			const agent = members?.find(item => item.id === clientId);
			setRecordPoint({ ...recordPoint(), recordingId: recordingId, userName: agent.user.name, userRole: 'agent', userId: agent.user.id });
			//系统录像recordingId
			// AgentService.setRecordingAlertInformation({ systemRecordingId: recordingId, type: 'system' });
			console.log('answerResult:', agent, members, clientId);
			dispatch(setSessionData({ ...session, agentClientId: clientId, roomId, members, publicationId, sessionId: data.sessionId }));
			// onTextMessage(onTextMessageEvent);
			// onResourceMessage(onResourceMessageEvent);
			// onCcsDrop(onCcsDropEvent);
			getSessionData(AgentService.sessionId);
			const customerClientId = members?.find(item => item.role === 'customer')?.id || '';
			if (customerClientId && isScreenSyncCall()) {
				setScreenSyncState({ ...screenSyncState(), clientId: customerClientId });
				startCoBrowsing('request-customer-size');
			}
			getTestimoneyData(AgentService.bizScenarioId);
			getVariablesData(AgentService.bizScenarioId);
			getTTSSwitch(AgentService.bizScenarioId);
			getAllRoleWithBusinessId(AgentService.bizScenarioId);
			getCustomerAndBusinessVariablesList({ sessionId: AgentService.sessionId, scenarioId: AgentService.bizScenarioId });
			getBizflowQualityRecordList(AgentService.sessionId);
			initZcoSubTitle();
			ZcoIM.setUserInfo(AgentService.user);
			ZcoIM.setOptions({
				maxUploadFileSize: AgentService.configure.maxUploadFileSize,
				resourceOriginUrlDomain: AgentService.configure.resourceOriginUrlDomain,
				resourceReplaceUrlDomain: AgentService.configure.resourceReplaceUrlDomain,
				urlMapping: typeof AgentService.configure.urlMapping === 'undefined' ? {} : AgentService.configure.urlMapping,
				token: AgentService.getToken()
			});
			ZcoIM.setWebTitle({ title: t('chat-window'), type: AgentService.acceptCallMode?.callMediaType, members: AgentService.sessionMembers?.length });
			// 人工工作流
			setHumanflowSteps(AgentService.getHumanflowSteps());
		}
	};

	//班组长强插会话
	const joinSessionWithChief = async () => {
		// AMS重连中 在重连中，点击接听，toast提示“操作失败”
		if (['reconnect_failed', 'reconnecting', 'offline'].includes(amsStatus)) {
			message.warning(t('action-failed'));
			return;
		}
		setLoading(true);
		try {
			await AgentService.joinSessionWithChief();
			receiveCustomizeMessage(message => receiveCustomizeMessageData(message));
		} catch (error) {
			console.log(error);
			setLoading(false);
		}
	};

	//接听
	const answerCall = async (mode: 'video' | 'audio' | 'im') => {
		setonRingView(false);
		setLoading(true);
		// AMS重连中 在重连中，点击接听，toast提示“操作失败”
		// if (['reconnect_failed', 'reconnecting', 'offline'].includes(amsStatus)) {
		// 	message.warning(t('action-failed'));
		// 	setLoading(false);
		// 	return;
		// }
		if (AgentService.isIMSession) {
			let result = null;
			try {
				if (mode === 'audio') {
					result = await AgentService.acceptUpgrade('audio');
				} else {
					result = await AgentService.acceptUpgrade('video');
				}
				setLoading(false);

				if (result) {
					AgentService.setIsIMSession(false);

					ZcoIM.setWebTitle({ title: t('chat-window'), type: mode, members: AgentService.sessionMembers?.length });
				}
			} catch (error) {
				console.warn('acceptUpgrade ', error);
				setLoading(false);
				InitializationData();
			}
		} else if (mode === 'im') {
			try {
				await AgentService.answerImCall();
				setLoading(false);
				AgentService.setIsIMSession(true);

				ZcoIM.setWebTitle({ title: t('chat-window'), type: 'im', members: AgentService.sessionMembers?.length });
			} catch (error) {
				console.warn('answerImCall ', error);
				setLoading(false);
				InitializationData();
			}
		} else {
			try {
				// const { audio = '', video = '' } = await AgentService.mediaDevices.validateDevicesSupport();
				// if (mode === 'video' && !video) {
				// 	Message.info('未检测到摄像头，自动切换为语音接听！');
				// 	AgentService.setAcceptCallMode({ ...AgentService.acceptCallMode, receiveMediaType: 'audio' });
				// }
				// if (mode === 'audio') {
				// 	AgentService.setAcceptCallMode({ ...AgentService.acceptCallMode, receiveMediaType: 'audio' });
				// }
				AgentService.setAcceptCallMode({ ...AgentService.acceptCallMode, receiveMediaType: mode });
				await AgentService.answer();
				setLoading(false);
				ZcoIM.setWebTitle({ title: t('chat-window'), type: mode, members: AgentService.sessionMembers?.length });
			} catch (error) {
				console.log('answer call error', error);
				hangUp({ code: 400, reason: 'answer error' });
				setLoading(false);
			}
		}

		ZcoIM.setUserInfo(AgentService.user);

		ZcoIM.setOptions({
			maxUploadFileSize: AgentService.configure.maxUploadFileSize,
			resourceOriginUrlDomain: AgentService.configure.resourceOriginUrlDomain,
			resourceReplaceUrlDomain: AgentService.configure.resourceReplaceUrlDomain,
			urlMapping: typeof AgentService.configure.urlMapping === 'undefined' ? {} : AgentService.configure.urlMapping,
			token: AgentService.getToken()
		});
	};

	const initZcoSubTitle = () => {
		const onAiStartSpeak = (status?: any, resp?: any, msgId?: any) => {
			return ivcs.agent.onAiStartSpeak(status, resp, msgId);
		};
		const onAiStartDone = (status?: any, resp?: any, msgId?: any) => {
			return ivcs.agent.onAiStartDone(status, resp, msgId);
		};
		const onMembersLeave = (info: any) => {
			return ivcs.agent.addEventListener('onAgentQuitSession', info);
		};
		const warpper = document.getElementById('customer-subtitle-warpper');
		// 加载字幕
		let subTitle = new ZcoSubTitle(onAiStartSpeak, onAiStartDone, onMembersLeave, '', { user: { clientId: AgentService.user?.clientId }, width: 256, height: 300, warpper, bottom: 14 });
		setZcoSubTitle(subTitle);
		ivcs.agent.onAiRecognitionMessage((resp: any) => {
			zcoSubTitle().setSubtitle(resp);
		});
	};

	//拒绝
	const rejectCall = async () => {
		if (AgentService.isIMSession) {
			try {
				const data = await AgentService.rejectUpgrade(AgentService.acceptCallMode?.receiveMediaType || 'video', { code: '0', message: 'normal' });
				console.log('reject ', data);
			} catch (error) {
				console.log('reject error', error);
			}
		} else {
			try {
				const data = await AgentService.rejectSession();
				console.log('reject ', data);
			} catch (error) {
				console.log('reject error', error);
			}
			InitializationData();
		}
		setonRingView(false);
	};

	//初始化数据
	const InitializationData = async () => {
		ZcoIM.clearZcoIMData();
		AgentService.sessionEnd();
		if (!AgentService.agentStatus.checkIn) {
			AgentService.removeCallProgressTimer();
		}
		zcoSubTitle() && zcoSubTitle().destory();
		setWhiteBoardBtnStatus('default');
		setSharePdfBtnStatus('default');
		clearStreams();
		onScreenSyncEnd();
		BusinessTaskMap.clearCompletedTask();
		BusinessTaskMap.clearTask();
		ReceiveBroadcastMap.clear();
		setBusiness([]);
		setAllMembers([]);
		clearSessionStorage();
		setCustomerSubmitInfo(initialUserInfo);
		dispatch(clearSessionData({}));
		dispatch(clearChatRecord());
		dispatch(clearCustomerStreamList());
		dispatch(clearAgentStreamList());
		dispatch(clearOtherStreamList());
		dispatch(clearRenderStream());
		setCustomerMembers([]);
		setIsScreenSyncCall(false);
		sendScreenSyncRef.current = false;
		setRecord({ recordId: '', publicationId: '', recordStatus: IBusinessStatus.IDLE, clientId: '' });
		setRecordPoint({ ...recordPoint(), recordingId: '' });
		setIsJoinSession(false);
		setonRingView(false);
		setTTSBoardCastStats('idle');
		setBoardCastModal(false);
		setEditModal(false);
		setStreams([]);
		setSmallStream([]);
		setRecordRegion({ recordId: '', publicationId: '', recordStatus: IBusinessStatus.IDLE, clientId: '' });
		setRequestWaiting({});
		AgentService.setIsIMSession(false);
		ZcoIM.setWebTitle({ title: t('chat-window'), type: '', members: 0 });
		setRecordingModalVisible(false);
		setHumanflowSteps(null);
		AgentService.agentMembers.clear();
		pauseRecordErrorAudio();
		clog.destroy();
	};

	//挂断
	const hangUp = async (reason: { code: number; reason: string; type?: string }) => {
		setLoading(false);
		console.log(reason, 'hangup reason');
		// 中止虚拟背景
		backgroundEffect.stopEffect(true);
		InitializationData();
		try {
			const data: any = await AgentService.hangup(reason);
			if (data?.code) {
				console.log('hangUp success', data);
			}
		} catch (error) {
			console.log('hangUp error', error);
		}
		closeCustomerViewMarkDialog(); // 关闭客户视图标记弹窗
	};

	//振铃时挂断
	const onRingCancelEvent = (reason: string | undefined) => {
		setonRingView(false);
		console.log(reason);
		InitializationData();
	};

	const onClientInfo = (client: Client) => {
		setLoading(false);
		if (!AgentService.sessionMembers.find(item => item.id === client.clientId)) return;
		const { clientId, streamInfo, role, userName } = client;
		let streamData: IStream = {
			id: streamInfo.id || '',
			label: streamInfo.streamLabel,
			audioOnly: streamInfo.audioOnly,
			clientId: clientId,
			videoId: streamInfo.streamLabel,
			muteStatus: false,
			streamMode: streamInfo.audioOnly ? 'audio' : 'video',
			role: role,
			isScreenSyncMode: streamInfo.isScreenSyncMode,
			userName: userName
		};
		updateStream(streamData);
	};

	//流加入
	const onStreamAddEvent = async (client: Client) => {
		console.log('onStreamAddEvent:', client, AgentService.sessionMembers);
		// if (!AgentService.sessionMembers.find(item => item.id === client.clientId)) return;
		const { clientId, streamInfo, role, userName, isRobot } = client;
		let streamData: IStream = {
			id: streamInfo.id || '',
			label: streamInfo.streamLabel,
			audioOnly: streamInfo.audioOnly,
			clientId: clientId,
			videoId: streamInfo.streamLabel,
			muteStatus: false,
			streamMode: streamInfo.audioOnly ? 'audio' : 'video',
			role: role,
			isScreenSyncMode: streamInfo.isScreenSyncMode,
			userName: userName,
			isRobot: isRobot
		};

		//TTS流
		if (streamData.label.indexOf('tts') > -1) {
			setBoardCastStream([...boardCastStream(), streamData]);
			return;
		}

		let members: IMembersProps = { id: streamData.id!, clientId: clientId, username: userName || '', userRole: role || 'normal', label: getMembersLabel(streamData.label) || null };
		/** 录屏流 */
		if (streamData.label === 'recordScreen' || streamData.label === 'recordScreen-Regional') return;
		if (streamData.label.indexOf('customer') === -1 && streamData.label.indexOf('agent') === -1 && streamData.audioOnly === true) {
			setAudioStreams([...audioStreams(), streamData]);
			let newStreams = [...streams()];
			if (newStreams.find(item => item.id?.includes(streamData.userName) || item.id === 'invite*')) {
				newStreams = newStreams.filter(item => !item.id?.includes('invite'));
				AgentService.removeOperationWithId(IOperationName.INVITE);
				setStreams(newStreams);
			}
			return;
		}
		streamAdd(streamData);
		AgentService.membersJoinSession(clientId, streamData);
		/** 非自己 */
		if (AgentService.user?.clientId !== clientId) {
			membersJoin(members);
		} else {
			console.log('setCurrentAgent:', members);
			// setAgentName(params.get('username')!);
		}
		if (streamData.label.indexOf('customer') > -1) {
			if (store.getState().customerStreams.length === 0) {
				dispatch(setCustomerStreamList([...customerStreams, streamData]));
			} else {
				dispatch(setAgentStreamList([...agentStreams, streamData]));
			}
		} else if (streamData.label.indexOf('agent') > -1) {
			// streamLabel.split('agent')[1] === params.get('username') && dispatch(setLoginData({ ...login, clientId }));
			// dispatch(setAgentStreamList([...agentStreams, streamData]));
		} else {
			dispatch(setAgentStreamList([...agentStreams, streamData]));
		}
		if (streamData.label.indexOf('screen') === -1 && streamData.label.indexOf('customer') === -1 && streamData.label.indexOf('agent') === -1) {
			dispatch(setAgentStreamList([...agentStreams, streamData]));
		}
		// 拉取变量值
		getCustomerAndBusinessVariablesList({ sessionId: AgentService.sessionId, scenarioId: AgentService.bizScenarioId });
	};

	//流退出
	const onStreamEndEvent = async (streamInfo: StreamEnd) => {
		console.log('onStreamEndEvent:', streamInfo);

		const streamLabel = streamInfo.data.streamLabel;
		if (streamLabel.indexOf('tts') > -1) {
			const streamData = boardCastStream().filter(item => item.label === streamLabel);
			setBoardCastStream(streamData);
		}
		if (streamLabel.indexOf('customer') > -1) {
			if (store.getState().customerStreams.length > 0 && store.getState().customerStreams[0].label === streamLabel) {
				dispatch(setCustomerLeave(streamLabel));
				let streamData = store.getState().agentStreams.find(item => item.label.indexOf('customer') > -1);
				dispatch(setCustomerStreamList([...customerStreams, streamData]));
				dispatch(setAgentLeave(streamData?.label));
			} else {
				dispatch(setAgentLeave(streamLabel));
			}
		} else if (streamLabel.indexOf('agent') > -1) {
			dispatch(setAgentLeave(streamLabel));
		} else {
			dispatch(setOtherLeave(streamLabel));
			dispatch(setAgentLeave(streamLabel));
			setAudioStreams([]);
		}

		if (streamLabel.includes('-screen')) {
			const tasks = [...BusinessTaskMap.BusinessQuene.values()];
			console.log('streamLabel:', tasks, streams(), streamLabel, streamInfo);
			tasks.map(async task => {
				if (task.name === IBusinessName.SCREEN_SHARE && AgentService.user?.userName === streamLabel.split('-')[0]) {
					await BusinessTaskMap.updateTaskStatus(task.clientId, IBusinessStatus.DONE, task.cmdId);
					await BusinessTaskMap.delTask(task.clientId);
					const receiver = AgentService.getCustomerMediaStream().find(item => item.clientId === task.clientId);
					saveStopScreenShareRecord(task.clientId);
					receiver && notifyOtherAgents(IBusinessName.SCREEN_SHARE, IBusinessStatus.DONE, receiver);
				}
			});
			const streamList = streams().filter(item => item.label !== streamLabel);
			setStreams(streamList);
		}
		const streamList = streams().filter(item => item.label !== streamLabel);
		setStreams(streamList);

		console.log(streamInfo, 'stream end', streams());
	};

	//访客离开会话
	const onCustomerQuitSessionEvent = async (info: any) => {
		console.log(info, 'customer quit session');
		AgentService.removeSessionMembers(info.data.id);
		setCustomerSubmitInfo(customerSubmitInfo().filter(item => item.userId !== info.data.user.id));
		let message = userInSessionRecord(info.data);
		if (AgentService.sessionId) {
			ZcoIM.setSystemMessage(info.data);
		}
		dispatch(setChatRecord(message));
		dispatch(setJoinMembers(info.data));
		membersLeave(info.data.id);
		streamEnd(info.data.id);
		AgentService.removeMembers(info.data.id);
		console.log('findTaskWithTaskName:', BusinessTaskMap.findTaskWithTaskName(IBusinessName.SCREEN_SHARE));

		if (BusinessTaskMap.findTaskWithTaskName(IBusinessName.SCREEN_SHARE).length === 0 && screenId()) {
			await endScreenShare(screenId());
			setScreenId('');
		}
		if (BusinessTaskMap.findTaskWithTaskName(IBusinessName.SHARED_WHITEDOARD).length === 0 && AgentService.whiteboardId) {
			const result = await deleteWhiteboard(AgentService.whiteboardId);
			setWhiteBoardBtnStatus('default');
			AgentService.whiteboardId = '';
		}
		if (BusinessTaskMap.findTaskWithTaskName(IBusinessName.SHARED_PDF).length === 0 && AgentService.pdfWhiteBoardId) {
			const result = await deletePdfWhiteboard(AgentService.pdfWhiteBoardId);
			AgentService.pdfWhiteBoardId = '';
			setSharePdfBtnStatus('default');
		}
		if (streams().length === 1) {
			hangUp({ code: 200, reason: 'customer quit' });
			MediaStatus.clearMediagData();
			dispatch(clearNetworkStatusData());
		} else {
			dispatch(setRemoteStatus({ id: info.data.id, status: 'reconnect_failed' }));
		}
		ZcoIM.setWebTitle({ title: t('chat-window'), type: AgentService.acceptCallMode?.callMediaType, members: AgentService.sessionMembers?.length });
	};

	//访客加入会话
	const onCustomerJoinSessionEvent = async (info: any) => {
		console.log(info, 'customer join session');
		AgentService.onCustomerJoinSessionEvent(info);

		let message = userInSessionRecord(info.data);
		ZcoIM.setSystemMessage(info.data);
		setCustomerSubmitInfo([
			...customerSubmitInfo(),
			{
				fullName: info.data.user.fullName || '',
				name: info.data.user.name || '',
				userId: info.data.user.id || '',
				idCard: info.data.user.idCard || '',
				phoneNumber: info.data.user.phoneNumber || ''
			}
		]);
		console.log(customerSubmitInfo());

		dispatch(setChatRecord(message));
		dispatch(setJoinMembers(info.data));
		AgentService.addSessionMembers(info.data);
		ZcoIM.setWebTitle({ title: t('chat-window'), type: AgentService.acceptCallMode?.callMediaType, members: AgentService.sessionMembers?.length });
	};

	const systemErrorEvent = (error: any) => {
		console.log('system error', error);
		// 1005 mcu异常，不主动断开。
		if (error.code === 1006 || error.code === 1007) {
			hangUp({ code: 400, reason: 'system error' });
		}
	};

	//ccsDropSession
	const onCcsDropEvent = (resp: { code: number; message: string; data?: any }) => {
		console.log('ccs drop', resp);
		hangUp({ code: 400, reason: 'ccs drop', type: resp.data?.reason === 'force' ? 'multiple' : 'customer-quit' });

		dispatch(setLocalCcsStatus('reconnect_failed'));
	};

	const sessionCcsErrorEventListener = (error: any) => {
		console.log('ccs socket io error', error);
		setTimeout(() => {
			hangUp({ code: 400, reason: 'socket io error', type: '' });
		}, 100);
	};

	const onAgentQuitSessionEvent = (info: any) => {
		console.log('agentQuitSession', info);
		let message = userInSessionRecord(info.data);
		// 过滤第一条坐席离开消息
		if (ZcoIM.chatMessage?.length > 0) {
			ZcoIM.setSystemMessage(info.data);
			dispatch(setChatRecord(message));
		}
		dispatch(setMembersLeave(info.data.id));
		membersLeave(info.data.id);
		streamEnd(info.data.id);
		agentLeaveSession(info.data.id);
		AgentService.removeMembers(info.data.id);
		AgentService.removeSessionMembers(info.data.id);
		if (AgentService.operationMap.get(IOperationName.INVITE) && AgentService.operationMap.get(IOperationName.INVITE).data.id === info.data.user.name) {
			AgentService.removeOperationWithId(IOperationName.INVITE);
			let newStreams = [...streams()];
			newStreams = newStreams.filter(item => !item.id?.includes(IOperationName.INVITE));
			setStreams(newStreams);
		}
		ZcoIM.setWebTitle({ title: t('chat-window'), type: AgentService.acceptCallMode?.callMediaType, members: AgentService.sessionMembers?.length });
	};

	const onAgentJoinSessionEvent = (info: any) => {
		console.log('onAgentJoinSession', info, session);
		AgentService.onAgentJoinSessionEvent(info);
		let message = userInSessionRecord(info.data);
		ZcoIM.setSystemMessage(info.data);
		dispatch(setChatRecord(message));
		dispatch(setJoinMembers(info.data));
		AgentService.addSessionMembers(info.data);
		ZcoIM.setWebTitle({ title: t('chat-window'), type: AgentService.acceptCallMode?.callMediaType, members: AgentService.sessionMembers?.length });
	};

	const onTextMessageEvent = (message: any) => {
		console.log(message, 'on text message');
		ZcoIM.setReceiveTextMessage(message);
		dispatch(setMessage(message));
	};

	const onResourceMessageEvent = (data: any) => {
		console.log('receive resource message,,', data);
		ZcoIM.setReceiveTextMessage(data);
		dispatch(setMessage(data));
	};

	// 监听访客端本地推送画面的媒体连接状态
	const onPublishMediaStatusEvent = (info: any) => {
		MediaStatus.setPublishMediaStatus(info);
	};
	// 监听渲染的远端画面的媒体连接状态
	const onRenderMediaStatusEvent = (info: any) => {
		// 排除本地坐席
		const { userInfo } = info;
		if (info?.userInfo?.clientId !== AgentService.user?.clientId) {
			MediaStatus.setRenderMediaStatus(info);
		}
	};

	/*获取用户刚开始进来提交的表单信息*/
	const dealWithCustomerSendMessage = (formId: number | string, userId: string) => {
		if (formId != '' && formId !== '-1') {
			//-1判断适配安卓端访客呼叫未提交资料
			getCustomerInfoFormData(formId, userId);
		} else {
			message.warning(t('client-no-submit-information'));
		}
	};

	/** 获取访客提交的个人信息*/
	const getCustomerInfoFormData = async (formId: number | string, userId: string) => {
		try {
			const { data } = await getuserforminfo(formId);
			console.log('get customer info success', data);
			if (data.code === 200) {
				setCustomerSubmitInfo([{ ...data.data, userId: Number(userId) }]);
			}
		} catch (error) {
			console.log('get customer info error', error);
		}
	};

	const saveCustomerForm = async (formId: string, sessionId: string) => {
		try {
			const { data } = await saveSessionForm({ sessionId: sessionId, formId: formId });
			console.log('save session from success', data);
		} catch (error) {
			console.log('save session from error', error);
		}
	};

	//获取聊天记录
	const getSessionData = async (sessionId: string) => {
		//575234012218110340
		try {
			const { data } = await getsessiondetail(sessionId);
			if (data.code === 200) {
				ZcoIM.setInitChatMessage(data.data);
			}
		} catch (error) {
			console.log(error);
			message.warning(t('get-chat-history-failed'));
		}
	};

	/**
	 * 判断当前技能组下，坐席是不是班组长
	 */
	const isChiefInGroupId = (serviceId: number | string) => {
		console.log('ring service skill', serviceId, chiefs());
		let isChief = false;
		chiefs().forEach(item => {
			if (item.data == serviceId) {
				isChief = true;
			}
		});
		console.log('is chiefs', isChief);
		return isChief;
	};

	const onRingCall = async (ringData: any) => {
		if (ringData) {
			if (ringData && ringData.userData && ringData.userData.formId) {
				setFormId(ringData.userData.formId);
				console.log('ringData:', ringData);
				if (ringData.userData.formId) {
					dealWithCustomerSendMessage(ringData.userData.formId, ringData.userData.userId);
					saveCustomerForm(ringData.userData.formId, ringData.sessionId);
				}
			}
			// setIsKickPerson(isChiefInGroupId(ringData.group));
			setRoomId(ringData.room);
			setonRingView(true);
			console.log('ringData:', ringData);
			// AgentService.setSessionId(ringData.sessionId);
			if (ringData.bizScenarioId) {
				AgentService.setBizScenarioId(ringData.bizScenarioId);
				getTestimoneyData(ringData.bizScenarioId);
				getVariablesData(AgentService.bizScenarioId);
				getTTSSwitch(ringData.bizScenarioId);
				getAllRoleWithBusinessId(AgentService.bizScenarioId);
				getCustomerAndBusinessVariablesList({ sessionId: AgentService.sessionId, scenarioId: ringData.bizScenarioId });
				getBizflowQualityRecordList(AgentService.sessionId);
			}

			dispatch(setSessionData({ ...session, ...ringData }));
			onCancelRing(onRingCancelEvent);
		}
	};

	const getTTSSwitch = async (bizScenarioId: string | number) => {
		try {
			const data: any = await getTTSOption(bizScenarioId);
			console.log(data, 'getTTSSwitch');
			if (data.data.agentTtsOption) {
				setTTSBoardCastStats('default');
			}
		} catch (error) {
			console.log(error, 'getTTSSwtich error');
			Message.error(t('get-tts-switch-failed'));
		}
	};

	const getTestimoneyData = async (bizScenarioId: string | number) => {
		try {
			const { data } = await getTestimoneyList(bizScenarioId);
			console.log(data, 'getTestimoneyData');

			AgentService.transcriptData = data.message;
		} catch (error) {
			console.log(error, 'getTestimoneyData error');
			Message.error(t('get-testimoney-list-failed'));
		}
	};

	const [, updateState] = useState<any>();
	const handleForceupdateMethod = useCallback(() => updateState({}), []);

	const getCustomerAndBusinessVariablesList = async (data: { sessionId: string; scenarioId: string | number }) => {
		let { sessionId, scenarioId } = data;
		if (!scenarioId) {
			scenarioId = session.bizScenarioId ? session.bizScenarioId : session.userData.service;
		}
		try {
			const { data } = await getCustomerAndBusinessVariables(sessionId, scenarioId);
			if (data.code === 200) {
				AgentService.setBusinessVariableList(data.data.filter((item: any) => !item.roleId));
				AgentService.setCustomerVariableList(data.data.filter((item: any) => item.roleId));
				handleForceupdateMethod();
			}
			console.log(data, 'getCustomerAndBusinessVariablesList success');
		} catch (error) {
			console.log(error, 'getCustomerAndBusinessVariablesList error');
			Message.error(t('get-variables-list-failed'));
		}
	};

	const getBizflowQualityRecordList = async (sessionId: string) => {
		try {
			const { data } = await getBizflowQualityRecord(sessionId);
			console.log(data, 'getBizflowQualityRecordList success');
			if (data.code === 200) {
				AgentService.qualityTesting.setQualityTestingResult(data.data);
				handleForceupdateMethod();
			}
		} catch (error) {
			console.log(error, 'getBizflowQualityRecordList error');
		}
	};

	const getVariablesData = async (bizScenarioId: string | number) => {
		const data = { scenId: bizScenarioId, initMode: '', isInvalid: '', page: 1, pageSize: 10000 };
		try {
			const resp = await getVariablesList(data);
			AgentService.collectionVariable = resp.data.data.data.map((item: any) => {
				return { id: item.id, key: item.name, property: item.type, content: '', initMode: item.initMode, scenId: item.scenId, url: item.url };
			});
			console.log(resp, 'getVariablesData success');
		} catch (error) {
			console.log(error, 'getVariablesData error');
			Message.error(t('get-variables-list-failed'));
		}
	};

	const getAllRoleWithBusinessId = async (bizScenarioId: string | number) => {
		try {
			const { data } = await getAllRoleWithBusiness(bizScenarioId);
			if (data.code === 200) {
				console.log(data, 'getAllRoleWithBusinessId success');
				AgentService.setAllRoleWithBusiness(
					data.data.map((item: any) => {
						return { id: item.id, name: item.name, scenId: item.scenId };
					})
				);
			}
		} catch (error) {
			console.log(error, 'getAllRoleWithBusinessId error');
		}
	};

	const receiveCustomizeMessageData = (message: any) => {
		console.log('receiveCustomizeMessageData:', message);
		dispatch(setCustomerMessage(message));
		dispatch(setCustomerMessageList([...customerMessageList, message]));
		if (message.data.type === 'screensync') {
			if (message.data.action === 'size') {
				console.log('receiveCustomizeMessage:', message.data);
				setScreenSyncState({ ...screenSyncState(), size: message.data.value });
			}
		}
		if (message.data.businessType === 'upgrade-stream') {
			const streamList = [...streams()];
			streamList.forEach((item, index) => {
				if (item.clientId === message.data.clientId) {
					console.log(item, message);
					streamList[index] = { ...item, streamMode: message.data.mode };
					if (message.data.mode === 'video') {
						AgentService.setAcceptCallMode({ ...AgentService.acceptCallMode, callMediaType: 'video' });
					}
				}
			});
			setStreams(streamList);
			// const newAllMediaStream = [...AgentService.getAllMediaSteams()];
			// newAllMediaStream.forEach((item, index) => {
			// 	if (item.clientId === message.data.clientId) {
			// 		newAllMediaStream[index] = { ...item, streamMode: message.data.mode };
			// 	}
			// });
			// AgentService.getAllMediaSteams() = newAllMediaStream;
			// AgentService.setOtherStreamData();
			AgentService.updateStreamByClientId(message.data.clientId, { streamMode: message.data.mode });
			console.log(AgentService.getAllMediaSteams(), 'AgentService.getAllMediaSteams()');
		}
	};

	const sendBusinessTask = () => {
		const receivers = customerMembers().map(item => item.clientId);
		sendBusiness(IBusinessName.SCREEN_SHOT, undefined, receivers);
	};

	const onAmsConnectStatusEvent = (status: string) => {
		// 'connected' | 'reconnect_failed' | 'reconnecting' | 'offline' | 'online' | 'ping-connected' | 'ping-timeout | 'error' | 'disconnect'
		if (status === 'reconnecting' || status === 'ping-timeout' || status === 'error' || status === 'offline') {
			// 未通话 | 振铃中 | 会话中： 右侧提示 “您与排队派工系统断开，尝试重连中...”
			openNotification(t('disconnect-from-dispatch-system-reconnect'));
		}

		if (status === 'reconnect_failed' || status === 'resume_error') {
			// 会话中：右侧提示 “您与排队派工系统断开，后续将无法收到派工呼叫，请于当前会话结束后重新登录”
			if (session.sessionId) {
			} else {
				console.log('onAmsConnectStatusEvent:', status);
				// 未通话 | 振铃中 ：覆盖蒙层，显示“您与排队派工系统断开，后续将无法收到派工呼叫，请重新登录”，
				openNotification(t('disconnect-from-dispatch-system-relogin'));
				setShowRelogin(true);
				setLoading(false);
				// remove listener
				if (navigate) {
					// widget 方式下保留
					AgentService.removeEventListener();
				}
				AgentService.removeCallProgressTimer();
			}
		}

		if (status === 'connected' || status === 'ping-connected') {
			closeNotification();
		}

		setAmsStatus(status);

		// if (status === 'disconnect') {
		// 	AgentService.setAgentStatus({ ...AgentService.agentStatus, logged: false, isChief: false, checkIn: false, otherWork: false, ready: false });
		// 	AgentService.setCheckedGroups([]);
		// 	AgentService.removeEventListener();
		// 	AgentService.removeCallProgressTimer();
		// 	ZcoIM.destory();
		// 	dispatch(resetAmsStatus());
		// 	nav2Login();
		// }
	};

	const onOtherReconnectingEvent = (resp: any) => {
		const { id } = resp.data;
		dispatch(setRemoteStatus({ id: id, status: 'reconnecting' }));
	};
	const onOtherResumeConnectEvent = (resp: any) => {
		const { id } = resp.data;
		dispatch(setRemoteStatus({ id: id, status: 'connected' }));
	};
	const onSessionConnectStatusEvent = (resp: any) => {
		dispatch(setLocalCcsStatus(resp));
	};

	const onSyncMessageEvent = (resp: any) => {
		if (resp.msgType === 'peer-status') {
			if (resp.data.clinetWhoInvitateCustomer && resp.data.status === 'joined') {
				ZcoIM.setBusinessMessage({
					createdAt: resp.createdAt,
					msgType: 'invite-customer',
					fromClientId: resp.data.clinetWhoInvitateCustomer.id,
					fromUserId: resp.data.clinetWhoInvitateCustomer.user.id,
					fromUserRole: resp.data.clinetWhoInvitateCustomer.role,
					fromUserName: resp.data.clinetWhoInvitateCustomer.user.name,
					fromUserAvatar: '',
					toUserInfo: '',
					fromUserInfo: '',
					invitation: '',
					data: resp.data
				});
				return;
			} else {
				return;
			}
		}
		if (resp.msgType === 'invitation-progress') {
			if (iFailedInviteProgressType.includes(resp.data.status)) {
				const fromUserInfo = AgentService.sessionMembers.find(item => item.id === resp.data.from.id);
				ZcoIM.setBusinessMessage({
					createdAt: '',
					msgType: 'invite',
					fromClientId: resp.data.from.id,
					fromUserId: '',
					fromUserRole: resp.data.from.role,
					fromUserName: fromUserInfo?.user.name,
					fromUserAvatar: '',
					toUserInfo: '',
					fromUserInfo: '',
					invitation: { failReason: resp.data.status },
					data: { agentId: resp.data.to.id, bizSceneName: resp.data.to.bizSceneName, type: resp.data.type }
				});
				return;
			} else {
				return;
			}
		}
		if (resp.msgType === 'peer-response' && resp.data.status === 'in-progress') return;
		if (resp.data.cmd === 'co-browsing' && resp.msgType === 'peer-cmd' && resp.data.data.type === 'request-customer-size') return;
		if (resp.data.cmd === 'co-browsing' && resp.msgType === 'peer-response' && resp.data.data.action === 'endScreenSync') return;
		if (resp.data.cmd === 'make-choice' || resp.data.cmd === 'third-nlp') return;
		if (resp.msgType === 'peer-cmd' && resp.data.cmd === 'view' && resp.data.data.type === 'messageSummary' && resp.data.data.nodeType === 'messageSummary') return;
		if (resp.msgType === 'peer-cmd' && resp.data.cmd === 'browsing-mark') return;
		if (resp.msgType === 'ai-checkout' && resp.data.status === 'detect-living-face') return;
		ZcoIM.setBusinessMessage(resp);
	};

	const onInvitationProgressEvent = (resp: any) => {
		console.log(resp, 'onInvitationProgressEvent');
		if (resp.type === 'invite-multiple' || resp.type === 'invite-multiple-human') {
			//邀请成功
			if ((resp.code === '403' || resp.code === '402') && !AgentService.operationMap.has(IOperationName.INVITE)) {
				AgentService.setOperationWithId(IOperationName.INVITE, { data: resp.to, initiator: resp.from.id });
			}
			//邀请失败
			if ((resp.code === '413' || resp.code === '414' || resp.code === '404' || resp.code === '415') && AgentService.operationMap.has(IOperationName.INVITE)) {
				AgentService.removeOperationWithId(IOperationName.INVITE);
				let newStreams = [...streams()];
				newStreams = newStreams.filter(item => !item.id?.includes(IOperationName.INVITE));
				setStreams(newStreams);
			}
		}
	};

	const onVariableChangeEvent = (resp: any) => {
		AgentService.clearBusinessVariableList();
		AgentService.clearCustomerVariableList();
		getCustomerAndBusinessVariablesList({ sessionId: AgentService.sessionId, scenarioId: AgentService.bizScenarioId });
	};

	const onRealTimeQualityEvent = (resp: any) => {
		AgentService.qualityTesting.setQualityTestingResult([resp.data]);
		handleForceupdateMethod();
		setTimeout(() => {
			const qualityTestingContainer: any = document.getElementById('widget-quality-testing');
			qualityTestingContainer.scrollTop = qualityTestingContainer.scrollHeight;
		}, 200);
	};

	const onRelogin = () => {
		closeNotification();
		hangUp({ code: 400, reason: 'ams reconnect failed' });
		if (navigate) {
			nav2Login();
			navigate('/login');
			window.location.reload();
		} else {
			// widget方式时登出处理
			AgentService.logout();
		}
	};

	const openNotification = (message: string) => {
		if (notificationStatus) {
			return;
		}
		notification.open({
			key: notificationKey,
			message: message,
			duration: 0,
			onClose: () => {
				setNotificationStatus(false);
			}
		});
		setNotificationStatus(true);
	};
	const closeNotification = () => {
		notification.destroy();
		setNotificationStatus(false);
	};

	const nav2Login = (code?: number) => {
		if (code === 403) {
			AgentService.entryOtherPage('otherPersonLogin');
		} else {
			AgentService.entryOtherPage('invalidAccount');
		}
		// reset state
		dispatch(logout());
		dispatch(resetNetworkStatus());
		AgentService.setAgentStatus({ ...AgentService.agentStatus, logged: false, isChief: false, checkIn: false, otherWork: false, ready: false, afterWork: false });
		AgentService.setCheckedGroups([]);
		AgentService.removeEventListener();
		AgentService.removeCallProgressTimer();
		dispatch(resetAmsStatus());
	};

	const onDropEvent = (data: any) => {
		console.log('on drop', data);
		hangUp({ code: data.code as any, reason: 'ccs drop', type: 'customer-quit' });
		if ([401, 402, 403, 404, 405].includes(Number(data.code))) {
			if (data.reason === 'accountDeleted') {
				AgentService.setErrorView(true);
				setServiceMonitoring(false);
				setAlertMessage(t('current-account-expired') as string);
				return;
			} else if (data.reason === 'accountDisabled') {
				AgentService.setErrorView(true);
				setServiceMonitoring(false);
				setAlertMessage(t('current-account-disabled') as string);
				return;
			}
			nav2Login(Number(data.code));
			setShowRelogin(true);
		}
	};

	const setErrorView = (visible: boolean) => {
		AgentService.setErrorView(visible);
		handleForceupdateMethod();
		nav2Login();
	};

	const { isImagePreviewHidden, isCallProgressHidden, userInfoHidden } = AgentService.configure.preferenceSettings;
	const { configure } = AgentService;

	const calculatorMainMaxWidth = (layout: ILayout): string | undefined => {
		if (layout === 'full') {
			return resizeWin(AgentService.rootContainer).Width > 1199 ? '540px' : '420px';
		} else if (layout === 'left' || layout === 'right' || layout === 'close') {
			return resizeWin(AgentService.rootContainer).Width > 1199 ? 'fit-content' : '100%';
		}
	};

	const changeTabs = (tab: ICurrentTab) => {
		configure.setCurrentTab(tab);
		setCurrentTab(tab);
	};

	const [requestWaiting, setRequestWaiting] = useState<any>({});
	const cancelRequest = async (media?: string) => {
		setLoading(true);
		const Promise = AgentService.cancelUpgrade('normal', media);
		Promise.then(s => {
			console.log('cancel-upgrade s', s);
			setRequestWaiting({});
			setLoading(false);
		}).catch(e => {
			console.log('cancel-upgrade e', e);
			setLoading(false);
		});
		// setLoading(false);
	};

	const onUpgrade = async (data: any) => {
		//  {type:'request-upgrade'|'accept-upgrade'|'reject-upgrade'|'cancel-upgrade',from:{},to:{},data:{media,roomId,roomToken,reason}}
		if (data) {
			const { type, reason, media } = data;
			if (type === 'request-upgrade') {
				// show request view
				setonRingView(true);
			} else if (type === 'accept-upgrade') {
				// hide waiting view
				setRequestWaiting({});
				// startVideo(videoLabel, callMediaType = 'video', onSuccess, onFailure)
				AgentService.startVideo();
				AgentService.setIsIMSession(false);
			} else if (type === 'reject-upgrade') {
				// hide waiting view
				setRequestWaiting({});
				if (reason?.message === 'membersOverrunNotAllowedUpgrade') {
					Message.error(t('unable-upgrade-due-to-new-visitor'));
				} else if (reason?.code === '60000') {
					if (media === 'video') {
						Message.error(t('client-no-authorize-microphone-or-camera'));
					} else {
						Message.error(t('client-no-authorize-microphone'));
					}
				} else {
					Message.normal(t('client-refuse-upgrade-request'));
				}
			} else if (type === 'cancel-upgrade') {
				// hide waiting view and answer view
				setRequestWaiting({});
				setonRingView(false);
				// 访客已取消音视频通话请求 client-cancel-upgrade-request
				Message.normal(t('client-cancel-upgrade-request'));
			}
		}
	};

	const getSysConfigList = async () => {
		try {
			let data = await getConfigList();
			console.log('获取系统设置下拉列表', data.data);
			// itemKey: 'screenWatermark'
			const item = data.data.list.find((item: any) => item.itemKey === 'screenWatermark');
			if (item?.status) {
				addScreenWatermark(item.itemData.param);
			}
		} catch (error) {
			console.log(error);
		}
	};

	const handleSummaryButtonClick = () => {
		setShowSummaryForm(true);
	};

	useEffect(() => {
		if (AgentService.agentStatus.afterWork) {
			setShowSummaryForm(true);
		}
	}, [AgentService.agentStatus.afterWork]);

	return (
		<Spin tip="Loading..." spinning={loading()} className="widget-loading" wrapperClassName="widget-agent-container-loading">
			<WidgetMainWrapper id="widget-agent-container" className="widget-agent-container">
				{/* 头部菜单模块 */}
				<Header style={{ height: '50px' }}>
					<HeaderMenu changeLayout={mode => configure.setLayout(mode as ILayout)} currentTab={currentTab} changeHeader={changeTabs}></HeaderMenu>
				</Header>
				{humanflowSteps() && humanflowSteps().length > 0 && <Humanflow steps={humanflowSteps()} onCurTips={tips => setCurTips(tips)} />}
				{record().recordStatus === IBusinessStatus.IN_PROGRESS ? <RecordScreenTimer /> : null}
				{configure.currentTab === 'agentManagement' ? (
					<WidgetLayout id="widget-agent-management-wrapper" style={{ marginTop: '50px' }}>
						<AgentManagement joinSessionWithChief={joinSessionWithChief} />
					</WidgetLayout>
				) : undefined}
				{configure.currentTab === 'serviceRecord' ? (
					<WidgetLayout id="widget-service-record-wrapper" style={{ marginTop: '50px', justifyContent: 'flex-start' }}>
						<ServiceRecord />
					</WidgetLayout>
				) : undefined}

				<WidgetLayout
					id="widget-main-wrapper"
					style={{
						display: ['agentManagement', 'serviceRecord'].includes(configure.currentTab) ? 'none' : '',
						marginTop: humanflowSteps() && humanflowSteps().length > 0 ? '105px' : '50px'
					}}
				>
					<WidgetLayoutSider
						id="chat-main-wrapper"
						width={resizeWin(AgentService.rootContainer).Width > 1199 ? 340 : 270}
						style={{ display: configure.layout === 'full' || configure.layout === 'left' ? 'block' : 'none', background: 'none' }}
					>
						{!userInfoHidden && <UserInforMation classname="user-info-box" usersInfo={customerSubmitInfo()}></UserInforMation>}
						{/* 聊天区域 */}
						{userInfoHidden ? (
							<FullWidgetMessage className="widget-message-box" id="widget-message-box"></FullWidgetMessage>
						) : (
							<NormalWidgetMessage className="widget-message-box" id="widget-message-box"></NormalWidgetMessage>
						)}
					</WidgetLayoutSider>

					<WidgetVideoWrapper style={{ maxWidth: calculatorMainMaxWidth(configure.layout) }}>
						{/* 视频容器 */}
						<div className="agent-video-box" id="agent-video-main-container">
							{recordRegion().recordStatus === IBusinessStatus.IN_PROGRESS && <RegionalScreenRecording />}
							<RecordPoint></RecordPoint>
							<VideoContainer layout={configure.layout} callMediaType={AgentService.acceptCallMode.callMediaType} hangup={() => hangUp({ code: 200, reason: 'noraml' })} />
							<ToolBar /*hangup={reason => hangUp({ code: 200, reason: reason })}*/ />
						</div>
					</WidgetVideoWrapper>

					<WidgetLayoutSider
						width={resizeWin(AgentService.rootContainer).Width > 1199 ? 340 : 270}
						style={{ display: configure.layout === 'full' || configure.layout === 'right' ? 'block' : 'none', background: '#fff' }}
					>
						{/* 业务处理 */}
						<VocationalDiv layout={configure.layout}>
							{humanflowSteps() && humanflowSteps().length > 0 && <SpeakingTips content={curTips} />}
							{!AgentService.configure.preferenceSettings.bizPannelHidden && (
								<Vocational classname="vocational-box" hasHumanflow={humanflowSteps() && humanflowSteps().length > 0}></Vocational>
							)}
							{!AgentService.configure.preferenceSettings.qualityTestingResultHidden ? (
								<QualityTestingResult hasHumanflow={humanflowSteps() && humanflowSteps().length > 0} />
							) : undefined}
						</VocationalDiv>
					</WidgetLayoutSider>
				</WidgetLayout>
			</WidgetMainWrapper>

			{/* 全局提示、弹窗 */}
			<OnRingModal visible={onRingView} callType={AgentService.acceptCallMode.receiveMediaType} onOK={answerCall} onCancel={rejectCall} imState={AgentService.isIMSession}></OnRingModal>
			<VariablePreview></VariablePreview>
			<AudioRing></AudioRing>
			<AudioRecordError></AudioRecordError>
			{AgentService.whiteboardId ? <WhiteBoard></WhiteBoard> : undefined}
			{AgentService.pdfWhiteBoardId ? <PdfWhiteBoard></PdfWhiteBoard> : undefined}
			{showRelogin() ? <ReconnectMessageBox onHangup={onRelogin} type="ams" /> : null}
			{AgentService.errorView ? <ErrorAlert setErrorView={setErrorView} message={alertMessage} /> : undefined}
			<WaitingBox visible={requestWaiting.status} media={requestWaiting.media} onCancel={cancelRequest} />
			<RecordingAlert
				visible={recordingModalVisible}
				content={recordingModalText}
				onClose={() => {
					setRecordingModalVisible(false);
					pauseRecordErrorAudio();
				}}
				onOk={() => {
					setRecordingModalVisible(false);
					pauseRecordErrorAudio();
					hangUp({ code: 400, reason: 'normal' });
				}}
			/>
			{isDialogCustomerViewMark.isShow && (
				<CustomerViewMarkDialog
					videoId={isDialogCustomerViewMark.videoId}
					clientId={isDialogCustomerViewMark.clientId}
					width={isDialogCustomerViewMark.width}
					height={isDialogCustomerViewMark.height}
					closeView={closeCustomerViewMarkDialog}
				/>
			)}
			{AgentService.sessionId && AgentService.isSessionSummaryOn() && <SummaryButton onClick={handleSummaryButtonClick} />}
			{AgentService.isSessionSummaryOn() && showSummaryForm && <SummaryForm type={AgentService.agentStatus.afterWork ? 'confirm' : ''} onClose={() => setShowSummaryForm(false)} />}
			{showChangePassword && <ChangePassword onClose={() => setShowChangePassword(false)} />}
		</Spin>
	);
};

export default Agent;
